package com.xianda.spring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

@Controller
@RequestMapping("/")
public class FileUploadController {

	// 访问路径为：http://ip:port/upload
	@RequestMapping(value = "/upload", method = RequestMethod.GET)
	public String upload() {
		return "files/fileUpload";
	}

	/**
	 * 文件上传具体实现方法（单文件上传）
	 *
	 */
	// @RequestMapping(value = "/upload", method = RequestMethod.POST)
	// @ResponseBody
	// public String upload(@RequestParam("file") MultipartFile file) {
	// if (!file.isEmpty()) {
	// try {
	// // 这里只是简单例子，文件直接输出到项目路径下。
	// // 实际项目中，文件需要输出到指定位置，需要在增加代码处理。
	// // 还有关于文件格式限制、文件大小限制，详见：中配置。
	// BufferedOutputStream out = new BufferedOutputStream(
	// new FileOutputStream(new File(file.getOriginalFilename())));
	// out.write(file.getBytes());
	// out.flush();
	// out.close();
	// } catch (FileNotFoundException e) {
	// e.printStackTrace();
	// return "上传失败," + e.getMessage();
	// } catch (IOException e) {
	// e.printStackTrace();
	// return "上传失败," + e.getMessage();
	// }
	// return "上传成功";
	// } else {
	// return "上传失败，因为文件是空的.";
	// }
	// }

	/**
	 * 多文件上传 主要是使用了MultipartHttpServletRequest和MultipartFile
	 *
	 */
	@RequestMapping(value = "/upload/batch", method = RequestMethod.POST)
	public String batchUpload(HttpServletRequest request) {
		List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
		MultipartFile file = null;
		BufferedOutputStream stream = null;
		for (int i = 0; i < files.size(); ++i) {
			file = files.get(i);
			String filePath = "D:\\log\\workspace\\";
			if (!file.isEmpty()) {
				try {
					byte[] bytes = file.getBytes();
					stream = new BufferedOutputStream(
							new FileOutputStream(new File(filePath + file.getOriginalFilename())));// 设置文件路径及名字
					stream.write(bytes);// 写入
					stream.close();
				} catch (Exception e) {
					stream = null;
					return "第 " + i + " 个文件上传失败 ==> " + e.getMessage();
				}
			} else {
				return "第 " + i + " 个文件上传失败因为文件为空";
			}
		}
		// return "上传成功:开始下载";
		return "redirect:/upload/download";
	}

	@RequestMapping(value = "/upload/download", method = RequestMethod.GET)
	public @ResponseBody String download(HttpServletResponse response) {
		String fileName = "service.log";
		response.setHeader("content-type", "application/octet-stream");
		response.setContentType("application/octet-stream");
		response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
		byte[] buff = new byte[1024];
		BufferedInputStream bis = null;
		OutputStream os = null;
		try {
			os = response.getOutputStream();
			bis = new BufferedInputStream(new FileInputStream(new File("D:\\log\\workspace\\" + fileName)));
			int i = bis.read(buff);
			while (i != -1) {
				os.write(buff, 0, buff.length);
				os.flush();
				i = bis.read(buff);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		System.out.println("下载完成");
		return null;
	}

}
